<template>
  <div>
    <div style="padding: 4px;">
      <el-button size="mini" icon="el-icon-plus" type="text" @click="onAddForm">添加</el-button>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column
        prop="label"
        label="菜单名称"
        width="400"
      />
      <el-table-column
        prop="path"
        label="路径"
        width="200"
      />
      <el-table-column
        prop="componentPath"
        width="150"
        label="组件地址"
      />
      <el-table-column
        prop="index"
        width="66"
        label="排序"
      />
      <el-table-column
        prop="uniqueCode"
        min-width="144"
        label="函数名"
      />
      <el-table-column
        fixed="right"
        label="操作"
        width="180"
      >
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="onViewForm(scope)">查看</el-button>
          <el-button type="text" size="small" @click="onEditForm(scope)">编辑</el-button>
          <el-popconfirm
            style="margin: 0 10px"
            confirm-button-text="好的"
            cancel-button-text="不用了"
            icon="el-icon-info"
            icon-color="red"
            title="将会删除所有子项！！！"
            @confirm="onDeleteEditForm(scope)"
          >
            <el-button slot="reference" type="text" size="small">删除</el-button>
          </el-popconfirm>
          <el-button v-if="scope.row.type === 1 || scope.row.type === 2" type="text" size="small">添加子项</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="收货地址" :visible.sync="editFormVisible">
      <el-form ref="editFormComponent" :model="editForm" size="small" label-width="80px">
        <el-form-item label="类型:" prop="type">
          <el-radio-group v-model="editForm.type" :disabled="formType === 'view'">
            <el-radio label="1">目录</el-radio>
            <el-radio label="2">菜单</el-radio>
            <el-radio label="3">Tab</el-radio>
            <el-radio label="4">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="父节点:" prop="parentId">
          <el-select v-model="editForm.parentId" :disabled="formType === 'view'" filterable>
            <el-option v-for="item in parentOptionList" :key="item.id" :label="item.label" :value="item.id">
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right; color: #8492a6; font-size: 12px">
                <span v-if="item.type === 1">目录</span>
                <span v-else-if="item.type === 2">菜单</span>
                <span v-else-if="item.type === 3">Tab</span>
                <span v-else-if="item.type === 4">按钮</span>
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜单名称:" prop="label">
          <el-input v-model="editForm.label" :readonly="formType === 'view'" autocomplete="off" />
        </el-form-item>
        <el-form-item label="图标:" prop="icon">
          <el-input v-model="editForm.icon" :readonly="formType === 'view'" autocomplete="off" />
        </el-form-item>
        <el-form-item label="排序:" prop="index">
          <el-input v-model="editForm.index" :readonly="formType === 'view'" type="number" autocomplete="off" />
        </el-form-item>
        <el-form-item label="隐藏:" prop="hidden">
          <el-switch v-model="editForm.hidden" :disabled="formType === 'view'" />
        </el-form-item>
        <el-form-item v-if="editForm.type === '1' || editForm.type === '2'" label="路径:" prop="path">
          <el-input v-model="editForm.path" :readonly="formType === 'view'" autocomplete="off" />
        </el-form-item>
        <el-form-item v-if="editForm.type === '2'" label="组件路径:" prop="componentPath">
          <el-input v-model="editForm.componentPath" :readonly="formType === 'view'" autocomplete="off" />
        </el-form-item>
        <el-form-item v-if="editForm.type === '1' || editForm.type === '2'" label="总是显示:" prop="alwaysShow">
          <el-switch v-model="editForm.alwaysShow" :disabled="formType === 'view'" />
        </el-form-item>
        <el-form-item v-if="editForm.type === '1'" label="重定向:" prop="redirect">
          <el-input v-model="editForm.redirect" :readonly="formType === 'view'" autocomplete="off" />
        </el-form-item>
        <el-form-item v-if="editForm.type === '4'" label="权限代码:" prop="uniqueCode">
          <el-input v-model="editForm.uniqueCode" :readonly="formType === 'view'" autocomplete="off" />
        </el-form-item>
        <!-- <el-form-item label="活动区域" :label-width="formLabelWidth">
          <el-select v-model="form.region" placeholder="请选择活动区域">
            <el-option label="区域一" value="shanghai" />
            <el-option label="区域二" value="beijing" />
          </el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="formType === 'view'" @click="onFormSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import store from '@/store'
import { flatRoute } from '@/utils/flat'
import { ref, computed } from '@vue/composition-api'
import { putRoute, deleteRoute, postRoute, getRoutes } from '@/api/role'

export default {
  data() {
    return {
      tableData: [],

      editFormComponent,
      editFormVisible: false,
      editForm: {},
      editFormBak: null,
      formType: 'create' // create, edit, view
    }
  },
  methods: {
    fetchRouteTree() {

    },
    initEditForm(form) {
      if (form) {
        form = { ...form }
        form.alwaysShow = !!form.alwaysShow
        form.hidden = !!form.hidden
        Object.keys(form).forEach(k => {
          if (typeof form[k] === 'number') {
            form[k] = form[k] + ''
          }
          if (typeof form[k] === 'undefined' || form[k] === null) {
            form[k] = ''
          }
        })

        return form
      }
      return {
        id: '',
        parentId: '',
        type: '1',
        label: '',
        path: '',
        index: '0',
        redirect: '',
        alwaysShow: false,
        hidden: false,

        uniqueCode: '',
        componentPath: ''
      }
    },
    packageEditForm(form) {
      form = { ...form }
      Object.keys(form).forEach(k => {
        if (k === 'type' || k === 'index') {
          form[k] = Number(form[k])
        }
      })
      return form
    },
    onEditForm(scope) {
      formType.value = 'edit'
      editFormVisible.value = true
      editForm.value = initEditForm(scope.row)
      editFormBak.value = initEditForm(scope.row)
    }
  },
  created() {
    this.fetchRouteTree()
    this.editForm = this.initEditForm()
  },
  computed: {
    parentOptionList() {
      let judge = null
      if (editForm.value.type === '1') {
        judge = function(route) {
          if (route.id === editForm.value.id) {
            return false
          }
          if (route.type === 1) {
            return true
          }
        }
      } else if (editForm.value.type === '2') {
        judge = function(route) {
          if (route.id === editForm.value.id) {
            return false
          }
          if (route.type === 1 || route.type === 2) {
            return true
          }
        }
      }
      const optionList = flatRoute(store.getters.routes, judge)
      if (editForm.value.type === '1' || editForm.value.type === '2') {
        optionList.unshift({
          id: '',
          label: '无'
        })
      }
      console.log(optionList)
      return optionList
    }
  },
  setup() {
    const tableData = ref([])

    function fetchRouteTree() {
      getRoutes()
        .then(res => {
          tableData.value = res.data.list
        })
    }
    fetchRouteTree()

    const editFormComponent = ref(null)
    const editFormVisible = ref(false)

    function initEditForm(form) {
      if (form) {
        form = { ...form }
        form.alwaysShow = !!form.alwaysShow
        form.hidden = !!form.hidden
        Object.keys(form).forEach(k => {
          if (typeof form[k] === 'number') {
            form[k] = form[k] + ''
          }
          if (typeof form[k] === 'undefined' || form[k] === null) {
            form[k] = ''
          }
        })

        return form
      }
      return {
        id: '',
        parentId: '',
        type: '1',
        label: '',
        path: '',
        index: '0',
        redirect: '',
        alwaysShow: false,
        hidden: false,

        uniqueCode: '',
        componentPath: ''
      }
    }

    function packageEditForm(form) {
      form = { ...form }
      Object.keys(form).forEach(k => {
        if (k === 'type' || k === 'index') {
          form[k] = Number(form[k])
        }
      })
      return form
    }

    const editForm = ref(initEditForm())
    const editFormBak = ref({})
    const formType = ref('create') // create, edit, view

    const parentOptionList = computed(() => {
      let judge = null
      if (editForm.value.type === '1') {
        judge = function(route) {
          if (route.id === editForm.value.id) {
            return false
          }
          if (route.type === 1) {
            return true
          }
        }
      } else if (editForm.value.type === '2') {
        judge = function(route) {
          if (route.id === editForm.value.id) {
            return false
          }
          if (route.type === 1 || route.type === 2) {
            return true
          }
        }
      }
      const optionList = flatRoute(store.getters.routes, judge)
      if (editForm.value.type === '1' || editForm.value.type === '2') {
        optionList.unshift({
          id: '',
          label: '无'
        })
      }
      console.log(optionList)
      return optionList
    })

    function onEditForm(scope) {
      formType.value = 'edit'
      editFormVisible.value = true
      editForm.value = initEditForm(scope.row)
      editFormBak.value = initEditForm(scope.row)
    }
    function editFormSubmit() {
      const reqData = {}
      Object.keys(editForm.value).forEach(key => {
        if (editFormBak.value[key] !== editForm.value[key]) {
          reqData[key] = editForm.value[key]
        }
      })
      putRoute(editForm.value.id, packageEditForm(reqData))
        .then(() => {
          editFormVisible.value = false
          store.dispatch('user/getRoute')
            .then(() => {
              store.state.user.breadCrumbEnforceReflesh()
            })

          fetchRouteTree()
        })
    }

    function onDeleteEditForm(scope) {
      const id = scope.row.id
      deleteRoute(id)
        .then(() => {
          store.dispatch('user/getRoute')
            .then(() => {
              store.state.user.breadCrumbEnforceReflesh()
            })
          fetchRouteTree()
        })
    }

    function onViewForm(scope) {
      formType.value = 'view'
      editFormVisible.value = true
      editForm.value = initEditForm(scope.row)
    }

    function onAddForm() {
      formType.value = 'create'
      editForm.value = initEditForm()
      editFormVisible.value = true
    }

    function addFormSubmit() {
      postRoute(packageEditForm(editForm.value))
        .then(() => {
          editFormVisible.value = false

          store.dispatch('user/getRoute')
            .then(() => {
              store.state.user.breadCrumbEnforceReflesh()
            })
          fetchRouteTree()
        })
    }

    function onFormSubmit() {
      if (formType.value === 'edit') {
        editFormSubmit()
      } else if (formType.value === 'create') {
        addFormSubmit()
      }
    }

    return {
      tableData,
      editFormComponent,
      editFormVisible,
      editForm,
      formType,
      parentOptionList,
      onEditForm,
      onViewForm,
      onFormSubmit,
      onDeleteEditForm,
      onAddForm

    }
  }

}
</script>

<style scoped>

</style>
